package org.rupa.common.util;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class HttpUtil {
    public static ResponseEntity<String> request(RestTemplate restTemplate, String url, Object obj) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.toJson(obj), headers);

        return restTemplate.exchange(
                url,
                HttpMethod.POST,
                httpEntity,
                String.class
        );
    }

    public static <T> T forwardRequest(RestTemplate restTemplate, String url, T obj) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.toJson(obj), headers);

        ResponseEntity responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                httpEntity,
                String.class
        );

        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new Exception("请求失败");
        }

        return (T) responseEntity.getBody();
    }
}
